﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Subtle.ViewModels;
using Subtle.Domain.Services.Interfaces;

namespace Subtle.Controllers
{
	/// <summary>
	/// Blog Configuration Controller
	/// </summary>
    public class BlogController : Controller
    {
		private IBlogService blogService;
		private IUserService userService;

		/// <summary>
		/// Initializes a Home Controller
		/// </summary>
		/// <param name="blogService"></param>
		/// <param name="userService"></param>
		public BlogController(IBlogService blogService, IUserService userService)
		{
			this.blogService = blogService;
			this.userService = userService;
		}

        /// <summary>
        /// ConfigureUser
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfigureUser()
        {
            return View();
        }

		/// <summary>
		/// ConfigureUser
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		[HttpPost]
		public ActionResult ConfigureUser(UserConfigureViewModel model)
		{
			if (ModelState.IsValid)
			{
				//The passwords have to match
				if (model.Password != model.ConfirmPassword)
				{
					ModelState.AddModelError("PasswordsDontMatch", "The passwords do not match");
					return View(model);
				}
				//Create the user
				var user = model.GetUser();
				if (userService.CreateValidatedUser(user) == Domain.Services.UserCreateStatus.Success)
				{
					Session.Add("UserID", user.ID);
					return RedirectToAction("ConfigureBlog");
				}
			}
			return View(model);
		}

		/// <summary>
		/// ConfigureBlog
		/// </summary>
		/// <returns></returns>
		public ActionResult ConfigureBlog()
		{
			return View();
		}


		/// <summary>
		/// ConfigureBlog
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		[HttpPost]
		public ActionResult ConfigureBlog(BlogConfigureViewModel model)
		{
			if (ModelState.IsValid)
			{
				var blogToCreate = model.GetBlog();
				blogToCreate.User = userService.GetUser(int.Parse(model.UserID));
				if (blogService.SetupBlog(model.GetBlog()))
				{
					return RedirectToAction("Index", "Home");
				}
			}
			return View(model);
		}
    }
}
